<template>
    <div class="m-win pic-to-pic-win-control">
        <div class="s-tit">以图搜图</div>
        <div class="up-box" :class="{'up-box-isdrag':isDrag}" id="up_box">
            <form onsubmit="return false;">
                <div class="tip-1">
                    将图片拖放到此处或 <el-upload class="pic-to-pic-elupload" action="" accept=".jpg,.png,.gif" :show-file-list="false" :http-request="pictureBefore"><a class="browser-upload">浏览</a></el-upload> 以选择文件
                </div>
                <div class="tip-2">或者</div>
                <div class="inp-paste-box">
                    <svg width="32" height="32" class="DFW_E" viewBox="0 0 32 32" version="1.1" aria-hidden="false"><path d="M13 21l-2-2 8-8 2 2-8 8zm1.1 3.1c-1.7 1.7-4.5 1.7-6.2 0-1.7-1.7-1.7-4.5 0-6.2l4-4L10 12l-4 4c-2.7 2.7-2.7 7.2 0 9.9s7.2 2.7 9.9 0l4-4L18 20l-3.9 4.1zm11.8-18c-2.7-2.7-7.2-2.7-9.9 0l-4 4 1.9 1.9 4-4c1.7-1.7 4.5-1.7 6.2 0 1.7 1.7 1.7 4.5 0 6.2l-4 4L22 20l4-4c2.7-2.7 2.7-7.2-.1-9.9z"></path></svg>
                    <input type="text" @paste="onPaste" @keyup="onInputFileSearch" placeholder="粘贴图像或URL">
                </div>
            </form>
            
            <div class="pic-to-pic-mask-container" :class="{'pic-to-pic-mask-searching':isSearching}">
                <div class="cus-loading-box">
                    <div class="cus-loading">
                    
                    </div>
                </div>
            </div>
        </div>
        <div class="or-str">
            或试试点击以下图片，找相似设计:
        </div>
        <div class="top-pics">
            <a @click="handleUrlToSearch(imgitem.image)" v-for="(imgitem,idx) in recommendlist" :key="idx"><img loading="lazy" :src="imgitem.image" alt=""></a>
            <!-- <a><img loading="lazy" src="http://t14.baidu.com/it/u=1776572993,1303539545&fm=224&app=112&f=JPEG?w=500&h=333" alt=""></a>
            <a><img loading="lazy" src="http://t14.baidu.com/it/u=1776572993,1303539545&fm=224&app=112&f=JPEG?w=500&h=333" alt=""></a>
            <a><img loading="lazy" src="http://t14.baidu.com/it/u=1776572993,1303539545&fm=224&app=112&f=JPEG?w=500&h=333" alt=""></a> -->
        </div>
    </div>
</template>

<script>
let SparkMD5 = require('spark-md5')
import api from '@/api/api'
import * as imageConversion from 'image-conversion'
export default {
    data(){
        return{
            isSearching:false,
            isDrag:false,
            recommendlist:[]
        }
    },
    props:{},
    async mounted(){
        let upEl=document.getElementById('up_box');
        upEl.addEventListener('drop', this.onDrop, false);
        upEl.addEventListener('dragover', this.onOndragover, false);
        upEl.addEventListener('dragenter', this.onOndragEnter, false);
        upEl.addEventListener('dragleave', this.onOndragLeave, false);
        
        let res=await api.getRecommendPics();
        // 正则将 http 转换为 https
        res.data.forEach(item => {
            item.image = item.image.replace(/^http:\/\//i, 'https://')
        })
        this.recommendlist=res.data;
    },
    destroyed(){
        // let upEl=document.getElementById('up_box');
        // upEl.removeEventListener('drop', this.onDrop, false);
        // upEl.removeEventListener('dragover', this.onOndragover, false);
        // upEl.removeEventListener('dragenter', this.onOndragEnter, false);
        // upEl.removeEventListener('dragleave', this.onOndragLeave, false);
    },
    methods:{
        onPaste(e){
            if(e.clipboardData&&e.clipboardData.files&&e.clipboardData.files.length>0){
                let _file=e.clipboardData.files[0];
                this.pictureBefore({file:_file})
            }
        },
        onInputFileSearch(e){
            let imgurl=e.target.value;
            let that=this;
            if(imgurl){
                new Promise(function(resolve, reject) {
                    var ImgObj = new Image();
                    ImgObj.src = imgurl;
                    ImgObj.onload = function(res) {
                        that.handleUrlToSearch(imgurl);
                    }
                    ImgObj.onerror = function(err) {
                        that.$amessage.warn('图片链接无效')
                    }
                })
            }
        },
        onOndragLeave(e){
            this.isDrag=false;
            e.preventDefault();
        },
        onOndragEnter(e){
            // this.isDrag=true;
            e.preventDefault();
        },
        onOndragover(e){
            this.isDrag=true;
            e.preventDefault()
        },
        async onDrop(e){
            // this.isDrag=true;
            e.preventDefault()
            if(e.dataTransfer.files.length>0){
                let file=e.dataTransfer.files[0];
                this.pictureBefore({file:file});
            }
        },
        handleUrlToSearch(url){
            let that = this;
            //方法二
            let canvas = document.createElement('canvas');
            let img = document.createElement('img');
            // 解决跨域 Canvas 污染问题

            img.setAttribute("crossOrigin", 'Anonymous');

            that.isSearching = true;

            that.isFocus = false;
            img.onload = function (e) {
                canvas.width = img.width;
                canvas.height = img.height;
                let context = canvas.getContext('2d');
                //绘制图片
                context.drawImage(img, 0, 0, img.width, img.height);
                canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

                const base64 = canvas.toDataURL('image/jpeg')
                localStorage.setItem('tmp_im_b64', base64);
                that.isFocus = false;
                if (that.$route.name == 'searchByImageList') {
                    location.href='/searchByImageList?t='+Date.parse(new Date())
                } else {
                    $('#app .pro-header .search-bx form').css('display','flex');
                    that.$router.push({ path: '/searchByImageList?t='+Date.parse(new Date()) })
                }
                return;
                //将canvas转base64码，然后创建一个a连接自动下载图片
                canvas.toBlob((blob) => {
                var reader = new FileReader();
                var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
                var spark = new SparkMD5.ArrayBuffer();
                var reader = new FileReader(); //创建读取文件的方法
                reader.readAsArrayBuffer(blobSlice.call(blob));
                reader.onload = async function (e) {
                    spark.append(e.target.result);
                    let formdata = new FormData();
                    formdata.append('file', blob);
                    formdata.append('pageNum', '1')
                    formdata.append('pageSize', '1')
                    let res = await api.imgToImgUpload(formdata);
                    var tmp_md5 = spark.end();

                    that.isFocus = false;
                    if (that.$route.name == 'searchByImageList') {
                    that.$router.replace({ path: '/searchByImageList?sign=' + tmp_md5 + '&surl=' + url })
                    } else {
                    that.$router.push({ path: '/searchByImageList?sign=' + tmp_md5 + '&surl=' + url })
                    }
                }
                }, "image/jpeg");
            }
            //将资源链接赋值过去，才能触发img.onload事件
            img.src = url
        },
        pictureBefore(file) {
            let that = this;
            that.isAgain = false;
            that.isSearching = true;
            var reader = new FileReader();
            var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
            var spark = new SparkMD5.ArrayBuffer();
            var reader = new FileReader(); //创建读取文件的方法
            imageConversion.compressAccurately(file.file, 1023).then(cpresFile => {
                reader.readAsArrayBuffer(blobSlice.call(cpresFile));
                reader.onload = async function (e) {
                const image = new Image();
                image.src = URL.createObjectURL(new Blob([e.target.result]));
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                image.onload = () => {
                    canvas.width = image.width
                    canvas.height = image.height
                    context.drawImage(image, 0, 0)
                    const base64 = canvas.toDataURL('image/jpeg')
                    localStorage.setItem('tmp_im_b64', base64);
                    that.isFocus = false;
                    if (that.$route.name == 'searchByImageList') {
                    location.href='/searchByImageList?t='+Date.parse(new Date())
                    } else {
                    that.$router.push({ path: '/searchByImageList?t='+Date.parse(new Date()) })
                    }
                }
                return;
                let _fdata = new FormData();

                _fdata.append('file', cpresFile);
                let res = await api.uploadImg(_fdata);
                if (res.data) {
                    let url = res.data;
                    spark.append(e.target.result);

                    let formdata = new FormData();
                    formdata.append('file', cpresFile);
                    // formdata.append('image',cpresFile);
                    formdata.append('pageNum', '1')
                    //formdata.append('page','1')
                    formdata.append('pageSize', '1')
                    res = await api.imgToImgUpload(formdata);
                    var tmp_md5 = spark.end();
                    that.isFocus = false;
                    if (that.$route.name == 'searchByImageList') {
                    that.$router.replace({ path: '/searchByImageList?sign=' + tmp_md5 + '&surl=' + url })
                    } else {
                    that.$router.push({ path: '/searchByImageList?sign=' + tmp_md5 + '&surl=' + url })
                    }
                } else {
                    that.isSearching = false;
                }
                }
            });

            // let url='https://image.gameuiux.cn/2021/03/17/73b4bd712cace08b48c5961818c2f073_list.jpg';
            //  //方法二
            // let canvas = document.createElement('canvas');
            // let img = document.createElement('img');
            // // 解决跨域 Canvas 污染问题

            // img.setAttribute("crossOrigin", 'Anonymous');
            // img.onload = function (e) {
            //     canvas.width = img.width;
            //     canvas.height = img.height;
            //     let context = canvas.getContext('2d');
            //     //绘制图片
            //     context.drawImage(img, 0, 0, img.width, img.height);
            //     canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
            //     //将canvas转base64码，然后创建一个a连接自动下载图片
            //     canvas.toBlob((blob) => {
            //         var reader = new FileReader();
            //         var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
            //         var spark = new SparkMD5.ArrayBuffer();
            //         var reader = new FileReader(); //创建读取文件的方法
            //         reader.readAsArrayBuffer(blobSlice.call(blob));
            //         reader.onload = async function(e) {
            //             spark.append(e.target.result);

            //             let formdata=new FormData();
            //             formdata.append('file',blob);
            //             formdata.append('pageNum','1')
            //             formdata.append('pageSize','1')
            //             let res=await api.imgToImgUpload(formdata);
            //             var tmp_md5 = spark.end();
            //             that.$router.push({path:'/searchForPictures?sign='+tmp_md5})
            //         }
            //     }, "image/jpeg");
            // }
            // //将资源链接赋值过去，才能触发img.onload事件
            // img.src = url


            // let formdata=new FormData();
            // // formdata.append('file',file.file);
            // formdata.append('hash','b5d6d9a17388a618083564b87fdea554')
            // formdata.append('pageNum','1')
            // formdata.append('pageSize','10')
            // let res=await api.imgToImgUpload(formdata);
            // this.$emit('onsearch',res.data);
        },
         handleCancel(){
            this.$emit('cancel');
         }
    }
}
</script>

<style lang="less">
.pic-to-pic-win-control{
    height:100%;
    padding-bottom:10px;
    .s-tit{
        font-size:15px;
        font-weight:500;
        color:#111111;
        line-height:49px;
        padding-left:18px;
    }
    .up-box{
        border:2px dashed #CBCBCB;
        border-radius:4px;
        margin:0px 18px;
        height:302px;
        text-align: center;
        padding-top:141px;
        background-image:url('../assets/icon_pic_to_pic_big_btn.png');
        background-position: center 40px;
        background-repeat:no-repeat;
        position: relative;
        .tip-1{
            font-size:21px;
            font-weight:500;
            color:#111111;
            .browser-upload{
                color:#00cdb2;
                margin:0px 5px;
            }
        }
        .tip-2{
            font-size:13px;
            color:#767676;
            font-weight:500;
            margin:23px 0px 19px 0px;
        }
        .inp-paste-box{
            height:41px;
            line-height:41px;
            width:300px;
            margin:0 auto;
            background:#EBEBEB;
            text-align: left;
            overflow: hidden;
            border-radius:20.5px;
            padding-left:17px;
            display: flex;
            align-items: center;
            .DFW_E{
                margin-right:12px;
                fill:#767676;
            }
            input{
                width:100%;
                background:#EBEBEB !important;
                border:none;
                outline: none;
                height:100%;
            }
        }
    }
    .up-box-isdrag{
        // background-color:#ebedf5;
        border-color:#00cdb2;
    }
    .or-str{
        font-size:13px;
        text-align: center;
        font-weight:500;
        color:#767676;
        margin-bottom:20px;
        margin-top:27px;
    }
    .top-pics{
        display: flex;
        align-items: center;
        justify-content: center;
        >a{
            display: inline-block;
            width:83px;
            height:57px;
            margin-right:16px;
            border-radius:4px;
            overflow: hidden;
            img{
                width:100%;
                height:100%;
                object-fit:cover;
            }
        }
    }
}
.pic-to-pic-elupload{
    display: inline-block;
}
.pic-to-pic-mask-container{
    position: absolute;
    top:0px;
    left:0px;
    right:0px;
    height:100%;
    z-index:-1;
    .cus-loading-box{
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        display:none;
    }
}
.pic-to-pic-mask-searching{
    background: #e9e9e9;
    z-index: 11;
    
    .cus-loading-box{
        display:flex;
    }
}
</style>